package petstore.web.servlet.cart;

import petstore.domain.CartItem;
import petstore.persistence.CartDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/cart")
public class CartServlet extends HttpServlet
{

    private String CART_PAGE = "/WEB-INF/jsp/cartPage/cartPage.jsp";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        HttpSession session = req.getSession(false);
        if(session == null || session.getAttribute("uid") == null)
        {
            //未登录，提示登录
            String cartMsg = "您还未登录，请登录。";
            req.setAttribute("cartMsg",cartMsg);
            System.out.println("未登录");
            req.getRequestDispatcher(CART_PAGE).forward(req,resp);
        }
        else
        {
            CartDaoImpl cartDao = new CartDaoImpl((int)session.getAttribute("uid"));
            List<CartItem> cartItemList = cartDao.getCartItemList();
            //显示购物车
            session.setAttribute("cartItemList",cartItemList);
        }
        req.getRequestDispatcher(CART_PAGE).forward(req,resp);
    }
}
